//
//  ARCommentInputController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/15.
//

import UIKit
import IQKeyboardManagerSwift
import SnapKit

/// 输入回调
protocol ARCommentInputControllerDelegate: NSObjectProtocol {
    
    /// 点击发送回调
    func inputVc(_ vc: ARCommentInputController, sentVale: ARCommentInputController.InputValue)
    
    // 音频相关的操作
    func inputVc(_ vc: ARCommentInputController, recordGestureDidChange gesture: UILongPressGestureRecognizer)
}

/// comment输入控制器
class ARCommentInputController: ARBaseViewController {
    
    // MARK: - Define
    
    /// 操作
    enum Function {
        case text, audio
    }
    
    enum InputValue {
        case text(sendText: String)
        case audio(path: String)
    }
    
    // MARK: - Property
    
    let functions: [Function]
    private var _currentFunction: Function {
        didSet {
            self.configCurrentFunction(_currentFunction)
        }
    }
    var currentFunction: Function {
        _currentFunction
    }
    
    var delegate: ARCommentInputControllerDelegate?
    
    // MARK: - Init
    
    init(functions: [Function]) {
        
        if functions.isEmpty {
            fatalError("Invalid functions")
        }
        
        self.functions = functions
        _currentFunction = functions.first!
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - LifeCycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        IQKeyboardManager.shared.enable = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        IQKeyboardManager.shared.enable = false
    }
    
    // MARK: - UI
    
    private func setupUI() {
        
        let singleFunction = isSingleFunction()
        
        let sendBtnShadowsView = UIView()
        sendBtnShadowsView.backgroundColor = .white
        sendBtnShadowsView.layer.cornerRadius = 16
        sendBtnShadowsView.layer.shadowColor = (UIColor(hexString: "#60CFFF") ?? .black).cgColor
        sendBtnShadowsView.layer.shadowOpacity = 0.4
        sendBtnShadowsView.layer.shadowOffset = CGSize(width: 3, height: 3)
        
        // 高度自适应
        self.view.addSubview(sendBtnShadowsView)
        self.view.addSubview(separatorLine)
        if singleFunction == false {
            self.view.addSubview(functionBtn)
        }
        self.view.addSubview(sendBtn)
        self.view.addSubview(textInputView)
        self.view.addSubview(audioInputView)
        
        separatorLine.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(1)
        }
        
        sendBtn.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(18)
            make.right.equalToSuperview().offset(-20)
            make.width.equalTo(64)
            make.height.equalTo(32)
            make.bottom.equalToSuperview().offset(-20)
        }
        
        sendBtnShadowsView.snp.makeConstraints { make in
            make.edges.equalTo(sendBtn)
        }
        
        textInputView.snp.makeConstraints { make in
            make.height.equalTo(36)
            make.centerY.equalTo(sendBtn)
            make.right.equalTo(sendBtn.snp.left).offset(-24)
            if singleFunction {
                make.left.equalToSuperview().offset(20)
            } else {
                make.left.equalTo(functionBtn.snp.right).offset(20)
            }
        }
        
        audioInputView.snp.makeConstraints { make in
            make.edges.equalTo(textInputView)
        }
        
        if singleFunction == false {
            functionBtn.snp.makeConstraints { make in
                make.width.height.equalTo(32)
                make.centerY.equalTo(sendBtn)
                make.left.equalToSuperview().offset(20)
            }
        }
        
        // 默认展示
        configCurrentFunction(_currentFunction)
    }
    
    // MARK: Helper
    
    /// 配置当前的function
    private func configCurrentFunction(_ function: Function) {
        // 每次都修改状态
        sendBtn.isEnabled = false
        textInputView.isHidden = function != .text
        audioInputView.isHidden = function != .audio
        if !isSingleFunction() {
            let nextFunction = findNextFunction()
            switch nextFunction { // 下一个function
            case .text:
                functionBtn.setImage(.init(named: "post_detail_input_textIcon"), for: .normal)
                break
            case .audio:
                functionBtn.setImage(.init(named: "post_detail_input_audioIcon"), for: .normal)
                break
            }
        }
    }
    
    /// 获取_currentFuncton 在 functions 中，下一个function
    private func findNextFunction() -> Function {
        if isSingleFunction() {
            return functions.first!
        }
        // 一定找得到
        var nextIndex = functions.firstIndex(of: _currentFunction)! + 1
        if nextIndex >= functions.count {
            nextIndex = 0
        }
        return functions[nextIndex]
    }
    
    private func isSingleFunction() -> Bool {
        return functions.count == 1
    }
    
    // MARK: - Action
    
    @objc private func sendBtnClicked(_ sender: UIButton) {
        
        switch _currentFunction {
        case .text:
            delegate?.inputVc(self, sentVale: .text(sendText: textField.text ?? ""))
            break
        case .audio:
            // Do nothing...
            break
        }
        
    }
    
    @objc private func functionBtnClick(_ sender: UIButton) {
        _currentFunction = findNextFunction() // 修改function即可
        self.view.endEditing(true)
    }
    
    // MARK: Public
    
    func clearText() {
        // 清除当前text
        if _currentFunction == .text {
            textField.text = ""
            sendBtn.isEnabled = false
        }
    }
    
    // MARK: - Lazy
    
    lazy var separatorLine: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexString: "#CCCCCC")
        view.isHidden = true
        return view
    }()
    
    // send btn
    private lazy var sendBtn: UIButton = {
        let btn = UIButton.ar.themeStyleButton(height: 32)
        btn.addTarget(self, action: #selector(sendBtnClicked(_:)), for: .touchUpInside)
        btn.setTitle(ARHelper.localString("Send"), for: .normal)
        return btn
    }()
    
    private lazy var functionBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.addTarget(self, action: #selector(functionBtnClick(_:)), for: .touchUpInside)
        btn.layer.shadowColor = UIColor.black.cgColor
        btn.layer.shadowOpacity = 0.1
        btn.layer.shadowOffset = .init(width: 1, height: 1)
        return btn
    }()
    
    private lazy var textField: UITextField = {
        let textField = UITextField()
        textField.delegate = self
        textField.font = ARHelper.font(12, weight: .regular)
        textField.attributedPlaceholder = NSAttributedString(string: ARHelper.localString("Enter your ideas..."), attributes: [
            .foregroundColor : UIColor.black.withAlphaComponent(0.3),
            .font : ARHelper.font(12, weight: .regular)
        ])
        return textField
    }()
    
    private lazy var textInputView: UIView = {
        let view = UIView()
        
        view.layer.cornerRadius = 18
        view.backgroundColor = UIColor(hexString: "#F2F2F2")
        
        view.addSubview(textField)
        
        textField.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(12)
            make.right.equalToSuperview().offset(-12)
        }
        
        return view
    }()
    
    private lazy var audioInputLabel: UILabel = {
        let label = UILabel()
        label.text = ARHelper.localString("Hold to talk")
        label.font = ARHelper.font(12, weight: .regular)
        label.textColor = UIColor(hexString: "#3ABBE9")
        return label
    }()
    
    private lazy var audioInputView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexString: "#E0F6FF")
        view.layer.cornerRadius = 18
        
        view.addSubview(audioInputLabel)
        audioInputLabel.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        // 长按手势
        let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(longPressGestureHandler(_:)))
        longPressGesture.minimumPressDuration = 0.5
        view.addGestureRecognizer(longPressGesture)
        
        return view
    }()
}

extension ARCommentInputController: UITextFieldDelegate {
    
    func textFieldDidChangeSelection(_ textField: UITextField) {
        self.sendBtn.isEnabled = !(textField.text ?? "").isEmpty
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.view.endEditing(true)
    }
    
}

/// audio recorder
fileprivate extension ARCommentInputController {
    
    @objc private func longPressGestureHandler(_ gesture: UILongPressGestureRecognizer) {
        delegate?.inputVc(self, recordGestureDidChange: gesture)
        
        switch gesture.state {
        case .began, .changed:
            self.audioInputLabel.text = ARHelper.localString("Release to send")
        case .ended, .cancelled, .failed:
            self.audioInputLabel.text = ARHelper.localString("Hold to talk")
        default: break
        }
        
    }
    
}
